package com.db.dbcloud;

import com.db.utils.ButtonStyleUtil;
import com.db.utils.ErrorJSONUtil;
import com.db.utils.FinalHttpUtil;
import com.db.utils.GsonUtil;
import com.db.utils.ServiceUtil;
import com.db.vo.User;
import com.google.gson.Gson;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

public class LoginActivity extends FinalActivity{
	@ViewInject(id = R.id.login_login_btn, click = "clickLogin")private ImageButton loginBtn;
	@ViewInject(id = R.id.login_register_btn, click = "clickRegister")private Button registerBtn;
	@ViewInject(id = R.id.login_autologin)private CheckBox autoLogin;
	@ViewInject(id = R.id.login_user)private EditText userText;
	@ViewInject(id = R.id.login_password)private EditText passText;
	
	private SharedPreferences sp;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_login);
		String userId = super.getIntent().getStringExtra("userid");
		if(userId != null){
			userText.setText(userId);
			autoLogin.setChecked(false);
			passText.setText("");
			sp = super.getSharedPreferences("userinfo", Activity.MODE_PRIVATE);
			sp.edit().putBoolean("autologin", false).putString("pass", "").commit();
		}
		ButtonStyleUtil.setButtonFocusChanged(loginBtn);
		ButtonStyleUtil.setButtonFocusChanged(registerBtn);
		if(userText.getText().length() > 6 && passText.getText().length() > 6){
			loginBtn.setEnabled(true);
		}else{
			loginBtn.setEnabled(false);
		}
		userText.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if(s.length() > 0){
					int pos = s.length() - 1;
					if(s.length() > 16){
						((Editable) s).delete(pos, pos + 1);
					}
				}
				if(s.length() <= 5){
					loginBtn.setEnabled(false);
				}else if(s.length() >= 6 && passText.getText().length() >= 6){
					loginBtn.setEnabled(true);
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		passText.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if(s.length() > 0){
					int pos = s.length() - 1;
					if(s.length() > 16){
						((Editable) s).delete(pos, pos + 1);
					}
				}
				if(s.length() <= 5){
					loginBtn.setEnabled(false);
				}else if(s.length() >= 6 && userText.getText().length() >= 6){
					loginBtn.setEnabled(true);
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		this.initConfig();
	}
	private void initConfig(){
		sp = super.getSharedPreferences("userinfo", Activity.MODE_PRIVATE);
		userText.setText(sp.getString("user", null));
		passText.setText(sp.getString("pass", null));
		autoLogin.setChecked(sp.getBoolean("autologin", false));
		if(sp.getBoolean("autologin", false)){
			ajaxLogin();
		}
	}
	public void checkAuto(){
		sp = super.getSharedPreferences("userinfo", Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("user", userText.getText().toString());
		if(autoLogin.isChecked()){
			editor.putString("pass", passText.getText().toString());
			editor.putBoolean("autologin", true);
		}else{
			editor.putBoolean("autologin", false);
		}
		editor.commit();
	}
	private void ajaxLogin(){
		FinalHttp finalHttp = FinalHttpUtil.getFinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("uid", userText.getText().toString());
		params.put("password", passText.getText().toString());
		finalHttp.configCharset("utf-8");
		String url = ServiceUtil.domainUrl + "/login";
		finalHttp.post(url, params, new AjaxCallBack<String>(){
			ProgressDialog pd = null;
			@Override
			public void onStart() {
				super.onStart();
				pd = new ProgressDialog(LoginActivity.this);
				pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    		pd.setCanceledOnTouchOutside(false);
	    		pd.setTitle("登录");
	    		pd.setMessage("正在登录...");
	    		pd.show();
			}
			@Override
			public void onLoading(long count, long current) {
				super.onLoading(count, current);
			}
			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				if(ErrorJSONUtil.isError(t)){
					Toast.makeText(LoginActivity.this, ErrorJSONUtil.getErrorMsg(t), Toast.LENGTH_LONG).show();
				}else{
					Gson gson = GsonUtil.getGson();
					User user = gson.fromJson(t, User.class);
					checkAuto();
					MainActivity.user = user;
					Intent intent = new Intent(LoginActivity.this, MainActivity.class);
					LoginActivity.this.startActivity(intent);
					LoginActivity.this.finish();
				}
				pd.hide();
			}
			@Override
			public void onFailure(Throwable t, String strMsg) {
				super.onFailure(t, strMsg);
				Toast.makeText(LoginActivity.this, "登陆失败，请检查网络问题", Toast.LENGTH_LONG).show();
				pd.hide();
			}
		});
	}
	public void clickLogin(View v){
		ajaxLogin();
	}
	public void clickRegister(View v){
		Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
		LoginActivity.this.startActivity(intent);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
		case RESULT_OK:
			userText.setText(data.getStringExtra("retuser"));
			passText.setText(data.getStringExtra("retpass"));
			autoLogin.setChecked(false);
			break;
		default:
			break;
		}
	}
}
